#!/usr/bin/perl
#
# Create a GNUPLOT command file from a history file
# Values to plot for are given on the command line
#
# NOTE: This creates 2 tempfiles and runs plot..

use English;
use Reportsub;

$usage = "Usage: $0 [-p] [-f date] mark... < inputfile\n";

while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-p") {
	# Scale by population
	$popscale = 1;
    } elsif ($opt eq "-f") {
	$fromdate = shift;
    } elsif ($opt eq "-d") {
	$delta = 1;
    } elsif ($opt eq "-onemonth") {
	@now = localtime();
	if ($now[4] == 0) {
	    # very primitive year wrap
   	    # note that now(4) is month 0-11; we do NOT add 1.
	    $now[4] = 12;
	    --$now[5];
	}
	$fromdate = sprintf("%4d-%02d-%02d", $now[5] + 1900, $now[4], $now[3]);
	print STDERR "Starting from $fromdate\n";
    } else {
	die $usage;
    }
}

@keys = @ARGV;
for $choose (@keys) {
    $doit{$choose} = 1;
}
if ($popscale) {
    getcountryinfo;
    $population{All} = $population{XW};
    $ylabel = "Users/Mpop";
} else {
    $ylabel = "Users";
}

while (<STDIN>) {
    chop;
    if (/:(\S+):/) {
	$date = $`;
	$selector = $1;
	$value = $';
#	if (!$doit{$selector}) {
#	    next;
#	}
	if ($popscale) {
	    $plot{$selector}{$date} = $value/$population{$selector};
	} else {
	    $plot{$selector}{$date} = $value;
	}
    } elsif (/^#Top countries: /) {
	for $x (split(/ /, $')) {
	    $doit{$x} = 1;
	}
    }
}
#open(PLOT, "|gnuplot") || die "Unable to open plotfile\n";
open(PLOT, ">-");
print PLOT <<EoF;
# Accept dates as input
set xdata time
set timefmt "%Y-%m-%d"
set xlabel "Year"
set format x "%d/%m"
set ylabel "$ylabel"
set terminal png
set size 0.8,0.5
#set xtics ("1991-01-01", "1992-01-01", "1993-01-01", "1994-01-01","1995-01-01", "1996-01-01", "1997-01-01", "1998-01-01", "1999-01-01")
set key top left
EoF

print PLOT "plot ";

for $val (keys(%doit)) {
    print PLOT ", " if $notfirst;
    $notfirst = 1;
    print PLOT "'-' using 1:2 title \"$val\" with lines";
}
print PLOT"\n\n";
#close PLOT;

# Plot it out again in squarish fashion
for $selector (keys(%doit)) {
    $donezero = 0;
    $prev = 0;
    for $date (sort(keys(%{$plot{$selector}}))) {
	if ($donezero eq 0 && !$fromdate) {
	    print PLOT "$date 0\n";
	    $donezero = 1;
	}
	if ($delta) {
	    $diff = $plot{$selector}{$date} - $prev;
	    print PLOT "$date $diff\n" if $date ge $fromdate;
	    $prev = $plot{$selector}{$date};
	} else {
	    print PLOT "$date $plot{$selector}{$date}\n" if $date ge $fromdate;
	}
    }
    print PLOT "end\n";
}
close DATA;

